package com.example.huixue.controller;

import com.example.huixue.common.PageResult;
import com.example.huixue.common.Result;
import com.example.huixue.entity.Favorite;
import com.example.huixue.service.FavoriteService;
import com.example.huixue.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class FavoriteController {
    
    private static final Logger logger = LoggerFactory.getLogger(FavoriteController.class);
    
    @Autowired
    private FavoriteService favoriteService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 添加收藏
     */
    @PostMapping("/resources/{resourceId}/favorite")
    public Result<?> addFavorite(@PathVariable Long resourceId, 
                                 @RequestHeader("Authorization") String token) {
        try {
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            
            // 处理mock token和真实JWT token
            Long userId;
            if (jwtToken.startsWith("mock-jwt-token-")) {
                // 处理mock token
                String userIdStr = jwtToken.replace("mock-jwt-token-", "");
                userId = Long.parseLong(userIdStr);
            } else {
                // 处理真实JWT token
                if (!jwtUtil.validateToken(jwtToken)) {
                    return Result.error(401, "请先登录");
                }
                Integer userIdInt = jwtUtil.getUserIdFromToken(jwtToken);
                userId = userIdInt.longValue();
            }
            
            Favorite favorite = favoriteService.addFavorite(userId, resourceId);
            logger.info("用户 {} 收藏资源 {}", userId, resourceId);
            
            return Result.success("收藏成功", favorite);
        } catch (RuntimeException e) {
            logger.warn("收藏失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("收藏过程发生错误", e);
            return Result.error("收藏失败，请稍后重试");
        }
    }
    
    /**
     * 取消收藏
     */
    @DeleteMapping("/resources/{resourceId}/favorite")
    public Result<?> removeFavorite(@PathVariable Long resourceId,
                                    @RequestHeader("Authorization") String token) {
        try {
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            
            // 处理mock token和真实JWT token
            Long userId;
            if (jwtToken.startsWith("mock-jwt-token-")) {
                // 处理mock token
                String userIdStr = jwtToken.replace("mock-jwt-token-", "");
                userId = Long.parseLong(userIdStr);
            } else {
                // 处理真实JWT token
                if (!jwtUtil.validateToken(jwtToken)) {
                    return Result.error(401, "请先登录");
                }
                Integer userIdInt = jwtUtil.getUserIdFromToken(jwtToken);
                userId = userIdInt.longValue();
            }
            
            // 先检查收藏是否存在
            boolean exists = favoriteService.isFavorited(userId, resourceId);
            if (!exists) {
                logger.warn("用户 {} 尝试取消收藏不存在的资源 {}", userId, resourceId);
                return Result.error("收藏不存在或已被取消");
            }
            
            favoriteService.removeFavorite(userId, resourceId);
            logger.info("用户 {} 取消收藏资源 {}", userId, resourceId);
            
            return Result.success("取消收藏成功");
        } catch (NumberFormatException e) {
            logger.warn("无效的用户ID格式: {}", e.getMessage());
            return Result.error(401, "无效的登录信息");
        } catch (RuntimeException e) {
            logger.warn("取消收藏失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("取消收藏过程发生错误", e);
            return Result.error("取消收藏失败，请稍后重试");
        }
    }
    
    /**
     * 检查收藏状态
     */
    @GetMapping("/resources/{resourceId}/favorite/status")
    public Result<?> checkFavoriteStatus(@PathVariable Long resourceId,
                                         @RequestHeader("Authorization") String token) {
        try {
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            
            // 处理mock token和真实JWT token
            Long userId;
            if (jwtToken.startsWith("mock-jwt-token-")) {
                // 处理mock token
                String userIdStr = jwtToken.replace("mock-jwt-token-", "");
                userId = Long.parseLong(userIdStr);
            } else {
                // 处理真实JWT token
                if (!jwtUtil.validateToken(jwtToken)) {
                    return Result.error(401, "请先登录");
                }
                userId = Long.valueOf(jwtUtil.getUserIdFromToken(jwtToken));
            }
            
            boolean isFavorited = favoriteService.isFavorited(userId, resourceId);
            
            return Result.success("获取收藏状态成功", isFavorited);
        } catch (Exception e) {
            logger.error("获取收藏状态失败", e);
            return Result.error("获取收藏状态失败，请稍后重试");
        }
    }
    
    /**
     * 获取用户收藏列表
     */
    @GetMapping("/favorites")
    public Result<?> getUserFavorites(@RequestParam(defaultValue = "1") int current,
                                      @RequestParam(defaultValue = "10") int size,
                                      @RequestHeader("Authorization") String token) {
        try {
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            
            // 处理mock token和真实JWT token
            Long userId;
            if (jwtToken.startsWith("mock-jwt-token-")) {
                // 处理mock token
                String userIdStr = jwtToken.replace("mock-jwt-token-", "");
                userId = Long.parseLong(userIdStr);
            } else {
                // 处理真实JWT token
                if (!jwtUtil.validateToken(jwtToken)) {
                    return Result.error(401, "请先登录");
                }
                userId = Long.valueOf(jwtUtil.getUserIdFromToken(jwtToken));
            }
            
            logger.info("获取用户 {} 的收藏列表，页码: {}, 大小: {}", userId, current, size);
            
            PageResult<Favorite> result = favoriteService.getUserFavorites(userId, current, size);
            
            logger.info("成功获取用户 {} 的收藏列表，总数: {}, 当前页记录数: {}", 
                       userId, result.getTotal(), result.getRecords().size());
            
            return Result.success("获取收藏列表成功", result);
        } catch (NumberFormatException e) {
            logger.warn("无效的用户ID格式: {}", e.getMessage());
            return Result.error(401, "无效的登录信息");
        } catch (Exception e) {
            logger.error("获取收藏列表失败, userId: {}, current: {}, size: {}", 
                        "unknown", current, size, e);
            return Result.error("获取收藏列表失败，请稍后重试");
        }
    }
    
    /**
     * 获取最近收藏的资源
     */
    @GetMapping("/favorites/recent")
    public Result<?> getRecentFavorites(@RequestParam(defaultValue = "5") int limit,
                                        @RequestHeader("Authorization") String token) {
        try {
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            
            // 处理mock token和真实JWT token
            Long userId;
            if (jwtToken.startsWith("mock-jwt-token-")) {
                // 处理mock token
                String userIdStr = jwtToken.replace("mock-jwt-token-", "");
                userId = Long.parseLong(userIdStr);
            } else {
                // 处理真实JWT token
                if (!jwtUtil.validateToken(jwtToken)) {
                    return Result.error(401, "请先登录");
                }
                userId = Long.valueOf(jwtUtil.getUserIdFromToken(jwtToken));
            }
            
            List<Favorite> favorites = favoriteService.getRecentFavorites(userId, limit);
            
            return Result.success("获取最近收藏成功", favorites);
        } catch (Exception e) {
            logger.error("获取最近收藏失败", e);
            return Result.error("获取最近收藏失败，请稍后重试");
        }
    }
    
    /**
     * 获取用户收藏数量
     */
    @GetMapping("/favorites/count")
    public Result<?> getUserFavoriteCount(@RequestHeader("Authorization") String token) {
        try {
            // 验证token格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "请先登录");
            }
            
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            
            // 处理mock token和真实JWT token
            Long userId;
            if (jwtToken.startsWith("mock-jwt-token-")) {
                // 处理mock token
                String userIdStr = jwtToken.replace("mock-jwt-token-", "");
                userId = Long.parseLong(userIdStr);
            } else {
                // 处理真实JWT token
                if (!jwtUtil.validateToken(jwtToken)) {
                    return Result.error(401, "请先登录");
                }
                userId = Long.valueOf(jwtUtil.getUserIdFromToken(jwtToken));
            }
            
            long count = favoriteService.getUserFavoriteCount(userId);
            
            return Result.success("获取收藏数量成功", count);
        } catch (Exception e) {
            logger.error("获取收藏数量失败", e);
            return Result.error("获取收藏数量失败，请稍后重试");
        }
    }
    
    /**
     * 获取资源被收藏数量
     */
    @GetMapping("/resources/{resourceId}/favorite/count")
    public Result<?> getResourceFavoriteCount(@PathVariable Long resourceId) {
        try {
            long count = favoriteService.getResourceFavoriteCount(resourceId);
            return Result.success("获取资源收藏数量成功", count);
        } catch (Exception e) {
            logger.error("获取资源收藏数量失败", e);
            return Result.error("获取资源收藏数量失败，请稍后重试");
        }
    }
} 